package com.lin.linchatgpt.openai.server.imple;



import com.lin.linchatgpt.entity.dto.MessageDTO;
import com.lin.linchatgpt.exception.LinException;
import com.lin.linchatgpt.openai.server.ChatMessageService;
import com.lin.linchatgpt.utils.OpenAiClientUtil;
import com.lin.linchatgpt.utils.ResultCode;


import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.billing.Subscription;

import lombok.extern.slf4j.Slf4j;


import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/6/3 11:14
 * @Description
 */
@Service
@Slf4j
public class ChatMessageServiceImpl extends BaseSendMessage implements ChatMessageService {


    @Override
    public Subscription validApiKey(String apikey) {
        OpenAiStreamClient client = OpenAiClientUtil.getOpenAiStreamClientUtil(new ArrayList<>(Collections.singletonList(apikey)));
        Subscription subscription;
        try {
            subscription = client.subscription();
        } catch (Exception e) {
            log.warn("Key是错误的{}", e.getMessage());
            throw new LinException(401, e.getMessage());
        }
        return subscription;
    }

    @Override
    public ResponseBodyEmitter sendMessage(MessageDTO messageDTO) {
        MessageHandleStrategy messageHandleStrategy = new MessageHandleStrategy();
        switch (messageDTO.getType()) {
            case 1:
                messageHandleStrategy.setHandleStrategy(new OrdinaryMessage(messageService));
                break;
            case 2:
                messageHandleStrategy.setHandleStrategy(new ModifyMessage(messageService));
                break;
            case 0:
                messageHandleStrategy.setHandleStrategy(new NewSubjectMessage(openAiClient, subjectService, messageService));
                break;
            default:
                throw new LinException(ResultCode.ERROR, "消息类型错误");
        }
        List<com.lin.linchatgpt.entity.Message> messages = messageHandleStrategy.sendMessage(messageDTO);


        return chatGPTCompletion(messages, messageDTO.getType());

    }

    @Override
    public ResponseBodyEmitter sendMessage(List<com.lin.linchatgpt.entity.Message> messages) {
        return chatGPTCompletion(messages, 2);
    }


}
